'use client';

import { useState, useEffect } from 'react';
import { BrandData } from '@/types';

interface BrandFilterProps {
  onBrandSelect?: (brand: string) => void;
  selectedBrand?: string;
  showHotBrands?: boolean;
}

export default function BrandFilter({ 
  onBrandSelect, 
  selectedBrand = '', 
  showHotBrands = false 
}: BrandFilterProps) {
  const [brands, setBrands] = useState<BrandData[]>([]);
  const [filteredBrands, setFilteredBrands] = useState<BrandData[]>([]);
  const [selectedLetter, setSelectedLetter] = useState<string>('');
  const [searchTerm, setSearchTerm] = useState('');

  // 获取字母索引
  const alphabetIndex = Array.from(new Set(brands.map(brand => brand.alphabet.toUpperCase())))
    .sort((a, b) => a.localeCompare(b, 'zh-CN'));

  useEffect(() => {
    // 动态导入品牌数据
    import('@/../public/brandData.js')
      .then((module) => {
        const brandData = module.default || [];
        setBrands(brandData);
        setFilteredBrands(brandData);
      })
      .catch((error) => {
        console.error('加载品牌数据失败:', error);
      });
  }, []);

  useEffect(() => {
    let filtered = brands;

    // 按字母筛选
    if (selectedLetter) {
      filtered = filtered.filter(brand => 
        brand.alphabet.toUpperCase() === selectedLetter
      );
    }

    // 按搜索词筛选
    if (searchTerm) {
      filtered = filtered.filter(brand => 
        brand.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        brand.brand.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 热门品牌筛选
    if (showHotBrands) {
      filtered = filtered.filter(brand => brand.hot === '1');
    }

    setFilteredBrands(filtered);
  }, [brands, selectedLetter, searchTerm, showHotBrands]);

  const handleBrandClick = (brand: BrandData) => {
    if (onBrandSelect) {
      onBrandSelect(brand.brand);
    }
  };

  const handleLetterClick = (letter: string) => {
    setSelectedLetter(selectedLetter === letter ? '' : letter);
  };

  const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTerm(e.target.value);
  };

  return (
    <div className="brand-filter">
      {/* 搜索框 */}
      <div className="mb-4">
        <input
          type="text"
          placeholder="搜索品牌..."
          value={searchTerm}
          onChange={handleSearchChange}
          className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
        />
      </div>

      {/* 字母索引 */}
      <div className="mb-4">
        <div className="flex flex-wrap gap-2">
          {alphabetIndex.map(letter => (
            <button
              key={letter}
              onClick={() => handleLetterClick(letter)}
              className={`px-3 py-1 rounded text-sm font-medium transition-colors ${
                selectedLetter === letter 
                  ? 'bg-blue-600 text-white' 
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
            >
              {letter}
            </button>
          ))}
        </div>
      </div>

      {/* 品牌列表 */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 xl:grid-cols-8 2xl:grid-cols-10 gap-4">
        {filteredBrands.map(brand => (
          <div
            key={brand.brand}
            onClick={() => handleBrandClick(brand)}
            className={`brand-item p-2 border rounded-lg cursor-pointer transition-all hover:shadow-md ${
              selectedBrand === brand.brand 
                ? 'border-blue-500 bg-blue-50' 
                : 'border-gray-200 hover:border-blue-300'
            }`}
          >
            {/* 品牌图标 */}
            <div className="flex items-center justify-center mb-2">
              <img 
                src={`/car-logo/${brand.brand}.png`}
                alt={brand.name}
                className="w-12 h-12 object-contain"
                onError={(e) => {
                  e.currentTarget.style.display = 'none';
                }}
              />
            </div>

            {/* 品牌信息 */}
            <div className="text-center">
              <div className="font-semibold text-sm text-gray-900">
                {brand.name}
              </div>
              <div className="text-xs text-gray-500 mt-1">
                {brand.brand}
              </div>
              {brand.hot === '1' && (
                <span className="inline-block px-2 py-1 text-xs bg-red-100 text-red-600 rounded-full mt-1">
                  热门
                </span>
              )}
            </div>
          </div>
        ))}
      </div>

      {filteredBrands.length === 0 && (
        <div className="text-center py-8 text-gray-500">
          未找到匹配的品牌
        </div>
      )}
    </div>
  );
}